#pragma once

#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include<pthread.h>
#include <string.h>
#include<functional>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Log.hpp"
#include "InetAddr.hpp"
using namespace std;

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    USAGE_ERROR,
    LISTEN_ERROR,
};
const static int defaultsockfd = -1;
const static int gbacklog = 16;

class TcpServer;
class ThreadData
{
public:
    ThreadData(int fd,InetAddr addr,TcpServer *s):sockfd(fd),clientaddr(addr),self(s)
    {

    }
    ~ThreadData()
    {

    }
public:
    int sockfd;
    InetAddr clientaddr;
    TcpServer *self;
};

using func_t=function<string(const string &)>;

class TcpServer
{
public:
    TcpServer(uint16_t port,func_t func) 
    : _port(port), _listensock(defaultsockfd), _isrunning(false),_func(func)
    {
    }
    void InitServer()
    {
        // 1.创建流式套接字
        //_sockfd = socket(AF_INET, SOCK_DGRAM, 0);udp
        _listensock = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensock < 0)
        {
            LOG(FATAL, "sockfd error,%s,%d\n", strerror(errno), errno);
            exit(SOCKET_ERROR);
        }
        LOG(DEBUG, "socket create success,socket:%d\n", _listensock);
        // 2.bind
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        int n = bind(_listensock, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(FATAL, "bind error,%s,%d\n", strerror(errno), errno);
            exit(BIND_ERROR);
        }
        LOG(DEBUG, "bind create success\n");
        // tcp是面向连接的，所以再通信之前必须先建立连接
        // tcp 启动，未来首先要一直等待客户的连接到来
        // 监听
        n = listen(_listensock, gbacklog);
        if (n < 0)
        {
            LOG(FATAL, "listen error,%s,%d\n", strerror(errno), errno);
            exit(LISTEN_ERROR);
        }
        LOG(DEBUG, "listen create success\n");
    }
    void Service(int sockfd, InetAddr client)
    {
        LOG(DEBUG, "get a new link,info %s:%d\n", client.Ip().c_str(), client.Port());
        std::string clientaddr = "[" + client.Ip() + ":" + std::to_string(client.Port()) + "]# ";
        while (true)
        {
            char inbuffer[1024];
            ssize_t n = recv(sockfd, inbuffer, sizeof(inbuffer),0);
            if (n > 0)
            {
                inbuffer[0];
                cout << clientaddr << inbuffer << endl;

                string result=_func(inbuffer);

                send(sockfd, result.c_str(), result.size(),0);
            }
            else if (n == 0)
            {
                // client 关闭了
                LOG(INFO, "%s quit\n", clientaddr.c_str());
                break;
            }
            else
            {
                LOG(ERROR, "read error\n", clientaddr.c_str());
                break;
            }
        }
        close(sockfd);
    }
    static void *HandlerSock(void* args)//IO通信和业务进行解耦
    {
        pthread_detach(pthread_self());
        ThreadData *td=static_cast<ThreadData*>(args);
        td->self->Service(td->sockfd,td->clientaddr);
        delete td;
        return nullptr;
    }
    void Loop() // 循环
    {
        _isrunning = true;
        // 不能直接接受数据，要先获取连接
        // 连接用 accept
        while (_isrunning)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = accept(_listensock, (struct sockaddr *)&peer, &len);
            if (sockfd < 0)
            {
                LOG(WARNING, "accept error\n");
                continue;
            }

            //多线程
            pthread_t t;
            ThreadData *td=new ThreadData(sockfd,InetAddr(peer),this);
            pthread_create(&t,nullptr,HandlerSock,td);//将线程分离
        }
    }
    ~TcpServer()
    {
        if (_listensock > defaultsockfd)
            close(_listensock);
    }

private:
    int _listensock;
    uint16_t _port;
    bool _isrunning;

    func_t _func;
};